package com.springboot.cloud.demos.ribbon.service;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.springboot.cloud.common.core.entity.vo.Result;
import com.springboot.cloud.common.core.exception.SystemErrorType;
import com.springboot.cloud.demos.entity.form.FollowForm;
import com.springboot.cloud.demos.entity.param.FollowQueryParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import java.util.LinkedHashMap;

@Service
public class FollowService {

    @Autowired
    RestTemplate restTemplate;

    @SentinelResource(fallback = "saveFallback")
    public Result save(@RequestBody FollowForm followForm) {
        Result result = restTemplate.getForEntity("http://producer/follow/getFollow?userId={1}&followUserId={2}", Result.class, followForm.getUserId(), followForm.getFollowUserId()).getBody();
        if (result.isSuccess() && result.getData() != null) {
            LinkedHashMap map = (LinkedHashMap) result.getData();
            String id = map.get("id").toString();
            restTemplate.put("http://producer/follow/{1}", followForm, id);
            return Result.success();
        }
        return restTemplate.postForEntity("http://producer/follow", followForm, Result.class).getBody();
    }

    @SentinelResource(fallback = "saveFallback")
    public Result update(@RequestBody FollowForm followForm) {
        restTemplate.put("http://producer/follow/{1}", followForm, followForm.getId());
        return Result.success();
    }

    @SentinelResource(fallback = "saveFallback")
    public Result deleteByMap(@RequestBody FollowQueryParam queryParam) {
        restTemplate.delete("http://producer/follow/deleteByMap?userId={1}&followUserId={2}", queryParam.getUserId(),queryParam.getFollowUserId());
        return Result.success();
    }


    public Result saveFallback(@RequestBody FollowForm followForm) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }


    public Result getFallback(@RequestParam("userId") String userId, @RequestParam("unitId") String unitId) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }

    public Result getFollow(String userId, String followUserId) {
        Result result = restTemplate.getForEntity("http://producer/follow/getFollow?userId={1}&followUserId={2}", Result.class, userId, followUserId).getBody();
        return result;
    }
}
